<template>
  <AuFormModal
    ref="formModalRef"
    v-model="showModal"
    :title="t(title)"
    :formList="formList"
    :formData="selfFormData"
    :modalProps="{
      width: 460
    }"
    :formProps="{
      class: '!w-[386px]'
    }"
    @formChange="formChange"
    @handleConfirm="handleConfirm"
  />
</template>

<script setup lang="ts">
import { AuFormModal } from "@/components/AuModal";
import { computed, nextTick, ref, watch } from "vue";
import { cloneDeep } from "lodash-unified";
import { tpmFormulaAdd, tpmFormulaUpd } from "@/api/teaPowder/formula";
import { ElMessage } from "element-plus";
import { getMaterialList } from "@/api/cabinet/formula";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

interface Props {
  modelValue: boolean;
  rowData: Object;
  versionId: string;
}

const props = defineProps<Props>();

const emits = defineEmits(["update:modelValue", "confirm"]);
const title = ref("");
const materialList = ref([]);
const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emits("update:modelValue", value);
  }
});
const MAX_WEIGHT = 50;
const MIN_WEIGHT = 3;

const validate = (rule: any, value: any, callback: any) => {
  const intReg = new RegExp(/^[0-9]\d*$/);
  if (!intReg.test(value)) {
    return callback(new Error(t("formula_detail.numberInput")));
  } else if (value < MIN_WEIGHT || value > MAX_WEIGHT) {
    return callback(
      new Error(
        t("formula_detail.numberRange", { min: MIN_WEIGHT, max: MAX_WEIGHT })
      )
    );
  }
  callback();
};

const validateFormula = (rule: any, value: any, callback: any) => {
  const intReg = new RegExp(/^[\u4e00-\u9fa5]+$/);
  if (!intReg.test(value)) {
    return callback(new Error(t("formula_detail.pleaseEnterChinese")));
  }
  callback();
};

const formList = ref([
  // {
  //   type: "input",
  //   key: "name",
  //   label: "物料名称",
  //   placeholder: "请输入物料名称",
  //   required: true,
  //   rules: [
  //     {
  //       validator: validateFormula,
  //       trigger: "blur"
  //     }
  //   ]
  // },
  {
    type: "select",
    key: "materialId",
    label: "formula_detail.material",
    placeholder: "formula_detail.pleaseSelectMaterial",
    labelKey: "name",
    valueKey: "material_id",
    options: [],
    required: true
  },
  // TODO: 这边要改 formula_detail.pleaseEnterModeOne, ${MIN_WEIGHT}-${MAX_WEIGHT}g
  {
    type: "input",
    key: "m1",
    label: "formula_detail.mode_one",
    placeholder: `formula_detail.pleaseEnterModeOne`,
    required: true,
    rules: [
      {
        validator: validate,
        trigger: "blur"
      }
    ]
  },
  {
    type: "input",
    key: "m2",
    label: "formula_detail.mode_two",
    // placeholder: `formula_detail.pleaseEnterModeTwo, ${MIN_WEIGHT}-${MAX_WEIGHT}g`,
    placeholder: `formula_detail.pleaseEnterModeTwo`,
    required: true,
    rules: [
      {
        validator: validate,
        trigger: "blur"
      }
    ]
  },
  {
    type: "input",
    key: "m3",
    label: "formula_detail.mode_three",
    placeholder: `formula_detail.pleaseEnterModeThree`,
    required: true,
    rules: [
      {
        validator: validate,
        trigger: "blur"
      }
    ]
  },
  {
    type: "input",
    key: "m4",
    label: "formula_detail.mode_four",
    placeholder: `formula_detail.pleaseEnterModeFour`,
    required: true,
    rules: [
      {
        validator: validate,
        trigger: "blur"
      }
    ]
  }
]);
const selfFormData = ref({});
const formModalRef = ref();

const formChange = (data: { key: string; value: any }) => {
  if (data.key === "materialId") {
    const find = materialList.value.find(
      (item: any) => item.material_id === data.value
    );
    formModalRef.value.setFormData({
      name: find.name
    });
  }
};

const handleConfirm = async (data: any) => {
  let service = tpmFormulaAdd;
  if (data?.id) {
    service = tpmFormulaUpd;
  } else {
    data.publishStatus = 1;
  }
  data.version = props.versionId;
  const res = await service(data);
  if (res.code == 200) {
    ElMessage({
      message: data?.id
        ? t("formula_detail.editSuccess")
        : t("formula_detail.addSuccess"),
      type: "success"
    });
    emits("update:modelValue", false);
    emits("confirm");
  }
};

const getMatList = async () => {
  const res = await getMaterialList({
    size: 0,
    start_page: 1,
    publish_status: 1
    // hiddenDeviceType: true, 高山乌龙 黑巧班章 桂花乌龙 茉莉花茶
    // device_type: "柜式机"
  });
  if (res.code == 200) {
    materialList.value = res.data;
    formModalRef.value.setFormProps("materialId", {
      options: res.data
    });
  }
};

watch(
  () => [props.modelValue, props.rowData],
  ([val, row]) => {
    if (val) {
      const rowData = cloneDeep(row) as { [key: string]: any };
      title.value = rowData?.id
        ? t("formula_detail.editMaterialRatio")
        : t("formula_detail.addMaterialRatio");
      getMatList();
      if (rowData?.id) {
        nextTick(() => {
          formModalRef.value.setFormData(row);
        });
      } else {
        nextTick(() => {
          // getVersionList();
          formModalRef.value.reset();
        });
      }
    }
  }
);
</script>
